<?php
class Server {
  public static function reset($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    
    if (!filter_var($req->user, FILTER_VALIDATE_EMAIL)) {
      echo '邮箱地址不正确';
      return;
    } else {
      $opts = new stdClass();
      $opts->cd = 't.account = :v1';
      $opts->cdv = array(':v1' => $req->user);
      $rslt = $orm->get('pb_ht_customer', NULL, NULL, NULL, NULL, $opts)->d;
      if (count($rslt) == 0) {
        echo '邮箱不存在';
        return;
      }
    }
    
    $rslt[0]->reset_exp = date('Y-m-d H:i:s', time());
    $rslt[0]->reset_key = Utils::unique();
    $orm->update('pb_ht_customer', $rslt[0]);
    
    if (!isset($_SESSION['profile'])) {
      $rslt2 = $orm->get('pb_ht_admin', NULL, NULL, NULL, NULL, NULL)->d;
      if (count($rslt2) > 0) {
        $_SESSION['profile'] = $rslt2[0];
      }
    }
    
    try {
      require_once '../3rd_party/phpMailer/class.phpmailer.php';
      $mailer = new PHPMailer();
      $mailer->IsSMTP();
      $mailer->Host = SMTP_HOST;
      $mailer->CharSet = "UTF-8";
      
      $mailer->SMTPAuth = true;
      $mailer->Username = SMTP_USER_ATDN;
      $mailer->Password = SMTP_PASS_ATDN;
      $mailer->From = $_SESSION['profile']->email;
      $mailer->FromName = $_SESSION['profile']->shop_name;
      
      $mailer->Body = '<a href="' . URL . HOME_DIR . $sys . '.php?i=' . $req->__id .'&__file=index_reset&key=' . $rslt[0]->reset_key . '">重置密码</a>';
      $mailer->Subject = 'Reset Password';
    
      $mailer->isHTML(true);
      $mailer->AddAddress($req->user, '');
      $mailer->Send();
    
      echo json_encode($rslt[0]);
    } catch (phpmailerException $e) {
      echo $e->errorMessage(); //Pretty error messages from PHPMailer
    } catch (Exception $e) {
      echo $e->getMessage(); //Boring error messages from anything else!
    }
  }
  
  public static function login($orm, $sys, $inst, $is_iframe) {
    unset($_SESSION['user']);
    setcookie('user', '', time() - 3600);
    
    $req = json_decode(Utils::get_param('req', '[]'));
    
    if (isset($req->recaptcha_challenge_field) && isset($req->recaptcha_response_field) && isset($_SESSION['tried']) && $_SESSION['tried'] > 3) {
      require_once '../3rd_party/recaptcha/recaptchalib.php';
      $resp = recaptcha_check_answer (RC_PRI,
                                      $_SERVER["REMOTE_ADDR"],
                                      $req->recaptcha_challenge_field,
                                      $req->recaptcha_response_field);
      if (!$resp->is_valid) {
        // What happens when the CAPTCHA was entered incorrectly
        $err = '验证码错误';
        $_SESSION['login_err'] = $err;
        $obj = new stdClass();
        $obj->err = $err;
        $obj->tried = $_SESSION['tried'];
        echo json_encode($obj);
        return;
      }
    }
    
    $opts = new stdClass();
    $opts->cd = 't.account = :v1';
    $opts->cdv = array(':v1' => $req->user);
    $rslt = $orm->get('pb_ht_customer', NULL, NULL, NULL, NULL, $opts)->d;
    
    $err = '';
    if (count($rslt) == 0) {
      $err = '邮箱不存在';
    } else if ($rslt[0]->password != md5($rslt[0]->salt . $req->pass)) {
      $err = '密码不正确';
    } else if ($rslt[0]->status == 0) {
      $err = '用户未激活';
    } else if ($rslt[0]->status == 2) {
      $err = '用户被屏蔽';
    }
    
    if ($err != '') {
      if (!isset($_SESSION['tried'])) {
        $_SESSION['tried'] = 1;
      } else {
        $_SESSION['tried']++;
      }
      
      $_SESSION['login_err'] = $err;
      $obj = new stdClass();
      $obj->err = $err;
      $obj->tried = $_SESSION['tried'];
      echo json_encode($obj);
      return;
    }
    
    unset($rslt[0]->password);
    $_SESSION['user'] = json_encode($rslt[0]);
    $_SESSION[SYS . $sys]->is_authorised = 1;
    unset($_SESSION['login_err']);
    unset($_SESSION['tried']);
    
  }
  
  public static function register($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    
    if (!filter_var($req->account, FILTER_VALIDATE_EMAIL)) {
      echo '邮箱地址不正确';
      return;
    } else {
      $opts = new stdClass();
      $opts->cd = 't.account = :v1';
      $opts->cdv = array(':v1' => $req->account);
      $rslt = $orm->get('pb_ht_customer', NULL, NULL, NULL, NULL, $opts)->d;
      if (count($rslt) > 0) {
        echo '邮箱已存在';
        return;
      }
    }
    
    if (strlen($req->password) < 6 || strlen($req->password) > 16) {
      echo '密码必须6-16位';
      return;
    }
    if ($req->password != $req->__retype) {
      echo '密码不一致';
      return;
    }
    if ($req->first_name == '' || $req->last_name == '') {
      echo '姓和名都不能为空';
      return;
    }
    
    $salt = Utils::unique();
    $req->track_id = Utils::unique();
    $req->password = md5($salt . $req->password);
    $req->salt = $salt;
    $req->reset_key = '';
    $req->reset_exp = '0000-00-00 00:00:00';
    $req->reg_date = date('Y-m-d', time());
    $req->email_required = 1;
    $req->status = 0;
    $req->ip = Utils::get_ip();
    $req->ip_place = '';
    $orm->add('pb_ht_customer', $req);
    $req->id = $orm->last_id();
    
    if (!isset($_SESSION['profile'])) {
      $rslt = $orm->get('pb_ht_admin', NULL, NULL, NULL, NULL, NULL)->d;
      if (count($rslt) > 0) {
        $_SESSION['profile'] = $rslt[0];
      }
    }
    
    try {
      require_once '../3rd_party/phpMailer/class.phpmailer.php';
      $mailer = new PHPMailer();
      $mailer->IsSMTP();
      $mailer->Host = SMTP_HOST;
      $mailer->CharSet = "UTF-8";
      
      $mailer->SMTPAuth = true;
      $mailer->Username = SMTP_USER_ATDN;
      $mailer->Password = SMTP_PASS_ATDN;
      $mailer->From = $_SESSION['profile']->email;
      $mailer->FromName = $_SESSION['profile']->shop_name;
      
      $mailer->Body = '<a href="' . URL . HOME_DIR . $sys . '.php?i=' . $req->__id .'&__file=index_active&t=' . $req->track_id . '">激活账号</a>';
      $mailer->Subject = 'Activate Now';
    
      $mailer->isHTML(true);
      $mailer->AddAddress($req->account, '');
      $mailer->Send();
      echo json_encode($req);
    } catch (phpmailerException $e) {
      echo $e->errorMessage(); //Pretty error messages from PHPMailer
    } catch (Exception $e) {
      echo $e->getMessage(); //Boring error messages from anything else!
    }
    
  }
}
?>